package Future_FutureTask_13;
import java.util.concurrent.*;
public class FutureTask直接使用_可取消任务 {
    public static void main(String[] args) {
        final int TASK_COUNT = 8;
        FutureTask<Integer>[] tasks = new FutureTask[TASK_COUNT];
        Thread[] threads = new Thread[TASK_COUNT];
        // 创建并启动任务
        for (int i = 0; i < TASK_COUNT; i++) {
            final int taskId = i;
            tasks[i] = new FutureTask<Integer>(new Callable<Integer>() {
                public Integer call() throws Exception {
                    System.out.println("任务 " + taskId + " 开始执行");
                    int sleepTime = 1000 + (int)(Math.random() * 2000);
                    for (int j = 0; j < 10; j++) {
                        Thread.sleep(sleepTime / 10);
                        if (Thread.currentThread().isInterrupted()) {
                            System.out.println("任务 " + taskId + " 被中断");
                            return -1;
                        }
                    }
                    return sleepTime;
                }
            });

            threads[i] = new Thread(tasks[i], "任务线程-" + i);
            threads[i].start();
        }

        // 随机取消部分任务
        for (int i = 0; i < TASK_COUNT / 2; i++) {
            int taskToCancel = (int)(Math.random() * TASK_COUNT);
            if (tasks[taskToCancel].cancel(true)) {
                System.out.println("已取消任务 " + taskToCancel);
            }
        }

        // 获取结果
        for (int i = 0; i < TASK_COUNT; i++) {
            try {
                if (!tasks[i].isCancelled()) {
                    Integer result = tasks[i].get();
                    System.out.println("任务 " + i + " 完成，耗时: " + result + "ms");
                }
            } catch (InterruptedException | ExecutionException | CancellationException e) {
                System.out.println("任务 " + i + " 结果获取异常: " + e.getClass().getSimpleName());
            }
        }
    }
}